#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define LISTEN_SZ 10

/*
客户端发送数据给服务端， 服务端接受后又返回给客户端
*/
int main(int argc, char const *argv[])
{

    ssize_t rbytes, sbytes;
    char buffer[1024] = {0};
    int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in server_addr, client_addr;
    
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(atoi(argv[2]));
    server_addr.sin_addr.s_addr = inet_addr(argv[1]);
    // 绑定服务端地址和端口
    int ret = bind(sock_fd, (struct sockaddr *) &server_addr, sizeof(server_addr));
    if (ret == -1) {
        perror("bind error");
        close(sock_fd)
        exit(EXIT_FAILURE);
    }
    // 监听连接
    ret = listen(sock_fd, LISTEN_SZ);
    if(ret == -1) {
        perror("listen error");
        close(sock_fd);
        exit(EXIT_FAILURE);
    }
    // accept

    socklen_t len = sizeof(client_addr);
    bzero(&client_addr, sizeof(struct sockaddr));
    /*
    The addrlen argument is a value-result argument: the caller must initialize it to contain the size (in  bytes)
       of the structure pointed to by addr; on return it will contain the actual size of the peer address.
       */
    int cfd = accept(sock_fd, (struct sockaddr *) &client_addr, &len);
    if (ret == -1) {
        perror("accept error");
        close(sock_fd);
        exit(EXIT_FAILURE);
    }
    printf("client ip is %s, client port is %d\n",  inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
    printf("sizeof(buffer) = %d\n", sizeof(buffer));
    rbytes = recv(cfd, buffer, sizeof(buffer) , 0); // 成功接受到的字节数
    if (rbytes == -1) {
        perror("recv error");
        close(sock_fd);
        exit(EXIT_FAILURE);
    }  else if(rbytes == 0) {
        printf("client is offine\n");
        close(sock_fd);
        exit(EXIT_SUCCESS);
    } else if (rbytes > 0) {
        // 将接受到的数据再发送会给客户端
        sbytes = send(cfd, buffer, sizeof(buffer), 0);
        if (sbytes == -1) {
            perror("send error");
            close(cfd);
            exit(EXIT_FAILURE);
        } 
    }

    close(cfd);
    close(sock_fd);

    return 0;
}
